package com.wolfpire.workflow.spring.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.jbpm.pvm.internal.model.ExecutionImpl;
import org.springframework.stereotype.Service;

import com.wolfpire.system.common.base.dao.IBaseHibernateDao;
import com.wolfpire.system.common.base.service.impl.BaseHibernateService;
import com.wolfpire.system.model.User;
import com.wolfpire.workflow.common.Constants;
import com.wolfpire.workflow.dao.ProInstanceDao;
import com.wolfpire.workflow.em.ProcessStatus;
import com.wolfpire.workflow.om.ProInstance;
import com.wolfpire.workflow.om.Workflow;
import com.wolfpire.workflow.spring.ProInstanceService;

@Service("proInstanceService")
public class ProInstanceServiceImpl extends BaseHibernateService<ProInstance, Long> implements ProInstanceService {

	@Resource private ProInstanceDao proInstanceDao;

	@Override
	public List<ProInstance> list(ProInstance entity) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	protected IBaseHibernateDao<ProInstance, Long> getEntityDao() {
		return this.proInstanceDao;
	}

	@Override
	public ProInstance addProInstance(Workflow workflow, ExecutionImpl pi,
			Long formId, User user, Map<String, Object> params) {
		ProInstance proInstance = new ProInstance();
		proInstance.setInstanceId(pi.getDbid());
		proInstance.setDeploymentId(workflow.getDeploymentId());
		proInstance.setWorkFlowId(workflow.getWorkFlowId());
		proInstance.setFormTypeId(Long.valueOf(workflow.getFormTypeId()));
		proInstance.setProName(workflow.getFlowName());
		proInstance.setNameId(pi.getId());
		proInstance.setUserId(user.getId());
		proInstance.setUserName(user.getNickName());
		proInstance.setStartTime(new Date());
		proInstance.setStatus(ProcessStatus.OPEN.getIndex());
		proInstance.setFormId(formId);
		String startNodeName = pi.findActiveActivityNames().toString();
		if(startNodeName.length()>3){
			startNodeName = startNodeName.substring(1,startNodeName.length()-1);
		}
		proInstance.setCurNode(startNodeName);
		//TODO:curUser
		proInstance.setUpdateTime(new Date());
		this.proInstanceDao.saveOrUpdate(proInstance);
		return proInstance;
	}

	@Override
	public void endMyProInstance(Long instanceId) {
		// 流程申请结束
		logger.info("======================== flow end ==========================");
		ProInstance proInstance = proInstanceDao.get(instanceId);
		proInstance.setEndTime(new Date());
		proInstance.setStatus(ProcessStatus.COMPLETED.getIndex());
		proInstance.setTimeLimitStatus(Constants.END);
		proInstance.setCurNode("");
		proInstance.setCurUser("");
		proInstance.setCurOrg("");
		proInstanceDao.save(proInstance);
	}

	@Override
	public ProInstance getByForm(Long formId, Long formTypeId) {
		return this.proInstanceDao.getProByFormId(formId, formTypeId);
	}
	
}
